const buildParamsString = (url: string) => {
  const app = getApp<IAppOption>()
  const { baseUrl, uniacid, version } = app.siteInfo
  const sessionid = wx.getStorageSync('sessionid') || ''

  const params: Record<string, string | number> = {
    i: uniacid,
    c: '',
    a: '',
    m: '',
    do: '',
    op: '',
    state: sessionid ? 'we7sid-' + sessionid : '',
    w7_request_secret: 1,
    from: 'wxapp',
    v: version
  };

  const queryString = url.split('?')[1]
  if (queryString) {
    const paramsArray = queryString.split('&');

    paramsArray.forEach(param => {
      const [key, value] = param.split('=');
      if (key !== 'i') {
        params[key] = isNaN(Number(value)) ? value : Number(value);
      }
    })
  }

  return baseUrl + '/app/index.php?' + Object.entries(params)
    .filter(([_, value]) => value !== undefined && value !== '')
    .map(([key, value]) => `${key}=${value}`)
    .join('&')
};

/**
 * request 请求结果是否错误
 */
const isError = (res: any) => {
  if (res) {
    if (res.hasOwnProperty('errno')) {
      return res.errno !== 0;
    }

    if (res.hasOwnProperty('type')) {
      return res.type !== 'success';
    }

    if (hasTitleTag(res)) {
      return true;
    }
  }

  return false;
};


/**
 * 字符串是否包含<title>标签
 */
const hasTitleTag = (str: string) => {
  return str && str.indexOf('<title>') > -1;
}

export const request = (options: WechatMiniprogram.RequestOption) => {
  return new Promise(async (resolve, reject) => {
    wx.request({
      url: buildParamsString(options.url),
      method: options.method || 'GET',
      data: options.data,
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      success: (res: any) => {
        if (res.hasOwnProperty('redirect')) {
          wx.navigateTo({ url: '/pages/login/index' })
        } else if (isError(res.data)) {
          const errorMessage = res.data.message || '服务器错误';
          wx.showToast({ title: errorMessage, icon: 'none', duration: 3000 });
          // reject(res.data)
        } else {
          resolve(res.data.data)
        }
      },
      fail: err => {
        wx.showToast({ title: err.errMsg, icon: 'none', duration: 3000 });
        reject(err)
      }
    })
  })
}